﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace NCRGEA.UserControls
{
    public partial class ucPrograms_Add : UserControl
    {
        private int _MemberID;
        public int MemberID
        {
            get
            {
                return _MemberID;
            }
            set
            {
                _MemberID = value;
                PopulateControls();
            }
        }

        DataTable dtParticipants;

        public ucPrograms_Add()
        {

            InitializeComponent();
            dtParticipants = new DataTable();
            dtParticipants.Columns.Add("FirstName");
            dtParticipants.Columns.Add("LastName");
            dtParticipants.Columns.Add("StartDate",DateTime.Now.GetType());
            dtParticipants.Columns.Add("Relation", (new int().GetType()));
            dtParticipants.Columns.Add("RelationShow");
        }

        private void PopulateControls()
        {
            grdParticipants.DataSource = dtParticipants;
            string sqlQry = @"SELECT
	                                ProgramID,
	                                Description,
                                    '$' + CAST(CAST(Amount as NUMERIC(10,2)) as VARCHAR) Amount
                                FROM
	                                memPrograms
                                WHERE
	                                ProgramTypeID NOT IN
		                                (SELECT
			                                pr.ProgramTypeID
		                                FROM
			                                memPlans pl
			                                INNER JOIN
				                                memPrograms pr
			                                ON
				                                pl.ProgramID=pr.ProgramID
		                                WHERE
			                                pl.MemberID=@MemberID AND
			                                pl.Active=1)";
            SqlParameter[] sParamArray = new SqlParameter[1];
            sParamArray[0] = new SqlParameter("@MemberID", _MemberID) { SqlDbType = SqlDbType.Int };
            DataTable result = AAL.DAL.ExecuteQuery(sqlQry, sParamArray);
            if (result != null)
            {
                if (result.Rows.Count == 0)
                {
                    //User can't add anymore programs
                    ShowProgramsList();
                    return;
                }

                cmbPrograms.DataSource = result;
                cmbPrograms.DisplayMember = "Description";
                cmbPrograms.SelectedIndex = 0;
            }


            string qry = @"SELECT Relation, Description FROM memRelations";
            DataTable results = AAL.DAL.ExecuteQuery(qry);
            if (results != null)
            {
                if (result.Rows.Count == 0)
                {
                    //Something bad happened.
                    ShowProgramsList();
                    return;
                }

                cmbRelation.DataSource = results;
                cmbRelation.DisplayMember = "Description";
                cmbRelation.SelectedIndex = 0;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ShowProgramsList();
        }

        private void ShowProgramsList()
        {
            //Flip back to the list of programs
            this.Parent.Controls.Add(new ucPrograms() { MemberID = _MemberID, Dock = DockStyle.Fill });
            this.Parent.Controls.Remove(this);
        }

        private void cmbPrograms_Leave(object sender, EventArgs e)
        {
            if (cmbPrograms.SelectedIndex == -1)
                cmbPrograms.SelectedIndex = 0;
        }

        private void cmbPrograms_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblAmount.Text = ((DataRowView)cmbPrograms.SelectedValue)["Amount"].ToString();
        }

        private void cmbRelation_Leave(object sender, EventArgs e)
        {
            if (cmbRelation.SelectedIndex == -1)
                cmbRelation.SelectedIndex = 0;
        }

        private void btnAddParticipant_Click(object sender, EventArgs e)
        {
            if (!ValidateParticipant())
                return;
            string FirstName = txtFirst.Text;
            string LastName = txtLast.Text;
            DateTime StartDate = dateStartDate.Value;
            int Relation = (int)((DataRowView)cmbRelation.SelectedValue)["Relation"];
            string RelationShow = ((DataRowView)cmbRelation.SelectedValue)["Description"].ToString();
            dtParticipants.Rows.Add(FirstName, LastName, StartDate, Relation, RelationShow);
            grdParticipants.DataSource = dtParticipants;

            txtFirst.Text = txtLast.Text = string.Empty;
            cmbRelation.SelectedIndex = 0;
        }

        private bool ValidateParticipant()
        {
            if (string.IsNullOrWhiteSpace(txtFirst.Text))
            {
                txtFirst.Focus();
                MessageBox.Show("Invalid First Name!");
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtLast.Text))
            {
                txtLast.Focus();
                MessageBox.Show("Invalid Last Name!");
                return false;
            }

            //Polygamy detection, lol
            int Relation = (int)((DataRowView)cmbRelation.SelectedValue)["Relation"];
            foreach (DataRow dr in dtParticipants.Rows)
                if ((int)dr["Relation"] == 1)
                    if (DialogResult.No == MessageBox.Show("Polygamy detected! Is this what you wanted?", "NCRGEA - Add Program", MessageBoxButtons.YesNo))
                        return false;
                    else
                        break;

            return true;
        }

        private void grdParticipants_KeyUp(object sender, KeyEventArgs e)
        {
            if (grdParticipants.SelectedRows.Count <= 0)
                return;
            if (e.KeyCode == Keys.Delete)
            {
                DialogResult dr = MessageBox.Show("Are you sure that you want to delete the selected particpant(s)?", "NCRGEA", MessageBoxButtons.YesNo);
                if (dr == DialogResult.No)
                    return;
                else
                    foreach (DataGridViewRow dgvr in grdParticipants.SelectedRows)
                        dtParticipants.Rows.Remove(((DataRowView)dgvr.DataBoundItem).Row);
                grdParticipants.DataSource = dtParticipants;
            }
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            int ProgramID = (int)((DataRowView)cmbPrograms.SelectedValue)["ProgramID"];
            DateTime StartDate = dateStartDate.Value;

            if (!AAL.UAL.RegisterProgram(ProgramID, _MemberID, StartDate, dtParticipants))
            {
                MessageBox.Show("An error occurred while registering for this program!");
            }
            else
            {
                ShowProgramsList();
            }
        }
    }
}
